<template>
  <div id="chat-container" class="chat-container">
    <main class="chat-main">
      <!-- 添加聊天历史展示组件区域 -->
      <div class="chat-history-container" v-if="!isMobile">
        <div class="history-header">
          <h3>聊天历史</h3>
        </div>
        <div class="history-list">
          <div 
            v-for="(history, index) in chatHistory" 
            :key="index"
            class="history-item"
            @click="loadHistory(history.id)"
          >
            <div class="history-title">{{ history.title }}</div>
            <div class="history-time">{{ history.time }}</div>
          </div>
        </div>
      </div>
      
      <div class="messages-container-wrapper">
        <div class="messages-container">
          <div 
            v-for="message in messages" 
            :key="message.id" 
            :class="['message', message.isUser ? 'user-message' : 'ai-message']"
          >
            <div class="message-content">
              <div class="avatar">
                <img :src="message.isUser ? require('~/assets/img/avatar-boy.gif') : require('~/assets/img/qq-icon-32.png')" alt="avatar">
              </div>
              <div class="text-content">
                <div class="text">{{ message.text }}</div>
              </div>
            </div>
          </div>
          <!-- Loading indicator for AI response -->
          <div v-if="isLoading" class="message ai-message">
            <div class="message-content">
              <div class="avatar">
                <img :src="require('~/assets/img/qq-icon.png')" alt="avatar">
              </div>
              <div class="text-content">
                <div class="text">正在思考中...</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="input-container">
          <div class="input-wrapper">
            <input 
              type="text" 
              class="message-input" 
              placeholder="输入消息..." 
              v-model="newMessage" 
              @keyup.enter="sendMessage" 
              :disabled="isLoading"
            />
            <button class="send-button" @click="sendMessage" :disabled="!newMessage.trim() || isLoading">
              发送
            </button>
          </div>
        </div>
      </div>
      
      <!-- 右侧留白区域 -->
      <div class="right-blank-space" v-if="!isMobile"></div>
    </main>
  </div>
</template>

<script>
  import chat from "@/api/chat";
  import cookie from "js-cookie";
  import axios from "axios";

  export default {
    data() {
      return {
        newMessage: '',
        messages: [
          { id: 1, text: '您好！我是AI助手，有什么可以帮助您的吗？', isUser: false }
        ],
        memoryId: 1, // Conversation context ID
        isLoading: false,
        chatMesg: {
          memoryId: '',
          message: ''
        },
        // 添加聊天历史数据
        chatHistory: [
          { id: 1, title: '数学问题讨论', time: '2023-05-15 14:30' },
          { id: 2, title: '英语语法咨询', time: '2023-05-14 10:15' },
          { id: 3, title: '编程问题求助', time: '2023-05-12 16:45' }
        ],
        // SSE连接实例
        eventSource: null,
        sessionId: this.generateSessionId(),
        isMobile: false
      };
    },
    methods: {
      generateSessionId() {
        return 'session_' + Math.random().toString(36).substr(2, 9);
      },
      initSSE() {
        if (process.client) {
          var url = process.env.BASE_API || 'http://localhost:8222'
          this.eventSource = new EventSource(url+`/ai/stream/${this.sessionId}`);
          
          this.eventSource.addEventListener('connect', (event) => {
            try {
              const data = JSON.parse(event.data);
              this.addMessage(data);
            } catch (e) {
              console.error('Error parsing connect event data:', e);
            }
          });
          
          this.eventSource.addEventListener('message', (event) => {
            try {
              const data = JSON.parse(event.data);
              console.log("event.data"+event.data)
              if (!data.isUser) {
                // 更新最后一条消息或添加新消息
                const lastMessage = this.messages[this.messages.length - 1];
                // 检查是否是同一批消息的一部分
                if (lastMessage && !lastMessage.isUser && !lastMessage.completed) {
                  // 更新现有消息内容
                  this.$set(lastMessage, 'text', (lastMessage.text || '') + (data.content || ''));
                } else {
                  // 添加新消息
                  this.addMessage({
                    text: data.content || data.text || event.data,
                    isUser: false,
                    id: this.messages.length + 1,
                    completed: false
                  });
                }
                this.$nextTick(() => {
                  this.scrollToBottom();
                });
              }
            } catch (e) {
              console.error('Error parsing message event data:', e);
              // 即使解析出错也显示原始数据
              this.addMessage({
                text: event.data,
                isUser: false,
                id: this.messages.length + 1,
                completed: false
              });
            }
          });
          
          this.eventSource.addEventListener('complete', (event) => {
            try {
              const data = JSON.parse(event.data);
              const lastMessage = this.messages[this.messages.length - 1];
              if (lastMessage && !lastMessage.isUser) {
                this.$set(lastMessage, 'completed', true);
              }
            } catch (e) {
              console.error('Error parsing complete event data:', e);
              const lastMessage = this.messages[this.messages.length - 1];
              if (lastMessage && !lastMessage.isUser) {
                this.$set(lastMessage, 'completed', true);
              }
            }
            this.isLoading = false;
          });
          
          this.eventSource.onerror = (error) => {
            console.error('SSE连接错误:', error);
            this.isLoading = false;
            // 确保在错误时也能正确处理
            const lastMessage = this.messages[this.messages.length - 1];
            if (lastMessage && !lastMessage.isUser && !lastMessage.text) {
              // this.$set(lastMessage, 'text', "抱歉，获取回复时出现问题，请稍后再试1。");
              this.$set(lastMessage, 'completed', true);
            } else if (!lastMessage || lastMessage.isUser) {
              // 如果没有消息或最后一条是用户消息，则添加错误消息
              this.addMessage({
                text: "抱歉，连接服务器时出现问题，请稍后再试。",
                isUser: false,
                id: this.messages.length + 1,
                completed: true
              });
            }
          };
        }
      },
      async clearHistory() {
        this.messages = [];
        this.isLoading = false;
        try {
          var url = process.env.BASE_API || 'http://localhost:8222'
          await axios.post(url+`/ai/clear/${this.sessionId}`);
        } catch (error) {
          console.error('清除历史失败:', error);
          this.$message.error("清除聊天历史失败");
        }
      },
      
      addMessage(message) {
        this.messages.push(message);
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      },
      
      scrollToBottom() {
        const container = document.querySelector('.messages-container');
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      },
      
      sendMessage() {
        console.log('sendMessage');
        if (this.newMessage.trim() && !this.isLoading) {
          // Add user message
          const userMessage = { 
            text: this.newMessage, 
            isUser: true, 
            id: this.messages.length + 1 
          };
          this.addMessage(userMessage);
          
          // Save current message
          const userQuery = this.newMessage;
          this.newMessage = '';
          
          // Get AI response from backend via SSE
          this.getAIResponse(userMessage.id, userQuery);
        }
      },
      
      // 添加加载历史记录方法
      loadHistory(historyId) {
        console.log('加载历史记录:', historyId);
        // 这里可以添加实际加载历史记录的逻辑
        // 例如从服务器获取历史对话记录
      },
      
      // 修改为使用SSE获取AI响应
      getAIResponse(messageId, userQuery) {
        this.isLoading = true;
        try {
          if(!cookie.get('we_token')){
            this.$message.warning("您还未登录，请先前往登录")
            this.isLoading = false;
            return false;
          }

          this.chatMesg.message = userQuery;
          this.chatMesg.sessionId = this.sessionId;
          this.chatMesg.user = '用户';

          chat.getResponseWithoutMessage(this.chatMesg).then(response => { 
            // 不需要在这里处理响应，因为SSE事件监听器会处理
          }).catch(error => {
            // console.error('Error getting AI response:', error);
            this.isLoading = false;
            // 显示错误消息给用户
            // const errorMessage = { 
            //   text: "抱歉，获取回复时出现问题，请稍后再试2。", 
            //   isUser: false, 
            //   id: this.messages.length + 1 
            // };
            // this.addMessage(errorMessage);
          });
        } catch (error) {
          // console.error('Error getting AI response:', error);
          this.isLoading = false;
          // 显示错误消息给用户
          const errorMessage = { 
            text: "抱歉，发送消息时出现问题，请稍后再试。", 
            isUser: false, 
            id: this.messages.length + 1 
          };
          this.addMessage(errorMessage);
        }
      },
      
      checkIsMobile() {
        if (process.client) {
          this.isMobile = window.innerWidth < 768;
        }
      }
    },
    
    mounted() {
      this.checkIsMobile();
      window.addEventListener('resize', this.checkIsMobile);
      this.initSSE();
      // Scroll to bottom on initial load
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    
    // 组件销毁前关闭SSE连接
    beforeDestroy() {
      if (process.client) {
        window.removeEventListener('resize', this.checkIsMobile);
      }
      if (this.eventSource) {
        this.eventSource.close();
      }
    }
  };
</script>

<style scoped>
  .chat-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 60px);
    background-color: #f5f5f5;
  }
  
  .chat-main {
    flex: 1;
    display: flex;
    overflow: hidden;
  }
  
  /* 添加聊天历史容器样式 */
  .chat-history-container {
    width: 200px;
    background-color: #ffffff;
    border-right: 1px solid #e0e0e0;
    padding: 16px;
    overflow-y: auto;
  }
  
  .history-header h3 {
    margin: 0 0 16px 0;
    font-size: 16px;
    color: #333;
  }
  
  .history-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .history-item {
    padding: 10px;
    border-radius: 8px;
    background-color: #f9f9f9;
    cursor: pointer;
    border: 1px solid #eee;
  }
  
  .history-item:hover {
    background-color: #f0f0f0;
  }
  
  .history-title {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
  }
  
  .history-time {
    font-size: 12px;
    color: #999;
  }
  
  .messages-container-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    display: flex;
    flex-direction: column;
  }
  
  .message {
    margin-bottom: 16px;
    max-width: 80%;
  }
  
  .user-message {
    align-self: flex-end;
  }
  
  .ai-message {
    align-self: flex-start;
  }
  
  .message-content {
    display: flex;
    align-items: flex-start;
  }
  
  .user-message .message-content {
    flex-direction: row-reverse;
  }
  
  .avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    overflow: hidden;
    margin: 0 8px;
  }
  
  .avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .text-content {
    max-width: calc(100% - 48px);
  }
  
  .user-message .text-content {
    text-align: right;
  }
  
  .text {
    padding: 12px 16px;
    border-radius: 18px;
    font-size: 14px;
    line-height: 1.5;
  }
  
  .ai-message .text {
    background-color: #ffffff;
    border: 1px solid #e0e0e0;
    border-top-left-radius: 4px;
  }
  
  .user-message .text {
    background-color: #007AFF;
    color: white;
    border-top-right-radius: 4px;
  }
  
  .input-container {
    padding: 16px;
    background-color: #ffffff;
    border-top: 1px solid #e0e0e0;
  }
  
  .input-wrapper {
    display: flex;
    align-items: center;
    background-color: #f0f0f0;
    border-radius: 20px;
    padding: 8px 16px;
  }
  
  .message-input {
    flex: 1;
    border: none;
    background: transparent;
    padding: 8px 0;
    font-size: 16px;
    outline: none;
  }
  
  .message-input:disabled {
    opacity: 0.6;
  }
  
  .send-button {
    background: transparent;
    border: none;
    cursor: pointer;
    padding: 8px;
    color: #007AFF;
    font-size: 14px;
  }
  
  .send-button:disabled {
    color: #cccccc;
    cursor: not-allowed;
  }
  
  /* 添加右侧留白区域样式 */
  .right-blank-space {
    width: 200px;
    background-color: #fafafa;
  }
  
  /* 移动端适配样式 */
  @media (max-width: 768px) {
    .chat-history-container {
      display: none; /* 在移动端隐藏聊天历史 */
    }
    
    .right-blank-space {
      display: none; /* 在移动端隐藏右侧空白区域 */
    }
    
    .chat-main {
      padding: 0; /* 移除内边距 */
    }
    
    .message {
      max-width: 90%; /* 在移动端减小消息气泡的最大宽度 */
    }
    
    .text {
      padding: 10px 14px; /* 减小文字内边距 */
      font-size: 16px; /* 增大字体以适应触屏 */
    }
    
    .message-input {
      font-size: 16px; /* 增大输入框字体 */
    }
    
    .chat-container {
      height: calc(100vh - 60px);
      border-radius: 0;
    }
    
    .messages-container {
      padding: 10px;
    }
    
    .input-container {
      padding: 10px;
    }
  }
</style>